package com.rocksdata.mc.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.alibaba.fastjson.JSON;
import com.ctz.commonframe.utils.DensityUtil;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ShapeHintView;
import com.ctz.commonframe.constant.DeviceInfo;
import com.ctz.commonframe.ui.BaseFragment;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.CampusAppManager;
import com.rocksdata.mc.business.location.UnreadManager;
import com.rocksdata.mc.entity.BannerInfo;
import com.rocksdata.mc.entity.CampusAppInfo;
import com.rocksdata.mc.entity.WidgetInfo;
import com.rocksdata.mc.ui.activity.MainActivity;
import com.rocksdata.mc.ui.adapter.BannerListAdapter;
import com.rocksdata.mc.view.AnnouncementWidgetView;
import com.rocksdata.mc.view.BaseWidgetView;
import com.rocksdata.mc.view.EmailWidgetView;
import com.rocksdata.mc.view.MeetingWidgetView;
import com.rocksdata.mc.R;
import com.rocksdata.mc.SharedPreferencesKey;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.entity.AppWidgetInfo;
import com.rocksdata.mc.ui.activity.WidgetManagerActivity;
import com.rocksdata.mc.view.AppWidgetView;
import com.rocksdata.mc.view.CampusCardWidgetView;
import com.rocksdata.mc.view.NewsWidgetView;
import com.rocksdata.mc.view.TimetableWidgetView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 陈堂正 on 2016/11/24.
 */
@ContentView(R.layout.fragment_home_page)
public class HomePageFragment extends BaseFragment {

    @ViewInject(R.id.layout_parent)
    private ScrollView layoutParent;
    @ViewInject(R.id.vp_banner)
    private RollPagerView vpBanner;
    @ViewInject(R.id.layout_widget)
    private LinearLayout layoutWidget;

    private List<AppWidgetInfo> widgetList = new ArrayList<>();
    private BusinessInterface.ICampusAppManager appManager;
    private Map<Integer, View> widgetViewMap = new HashMap<>();//存放组件
    private BaseWidgetView.OnEnterAppListener onEnterAppListener = new BaseWidgetView.OnEnterAppListener() {
        @Override
        public void onEnterApp(int widgetType) {
            switch (widgetType){
                case AppWidgetInfo.TYPE_ANNOUNCEMENT:
                    ((MainActivity)mContext).setCurrentFragmentIndex(1);
                    break;
                case AppWidgetInfo.TYPE_TIMETABLE:
                    CampusAppInfo timetableApp = new CampusAppInfo();
                    timetableApp.setName("课表");
                    CampusAppManager.skipToChildApplication(mContext, timetableApp);
                    break;
                case AppWidgetInfo.TYPE_NEWS:
                    CampusAppInfo newsApp = new CampusAppInfo();
                    newsApp.setName("校园新闻");
                    CampusAppManager.skipToChildApplication(mContext, newsApp);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        AnnouncementWidgetView widgetView = (AnnouncementWidgetView) widgetViewMap.get(AppWidgetInfo.TYPE_ANNOUNCEMENT);
        if(widgetView != null){
            widgetView.release();
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
//        if(UserInfoManager.isVisitor())
//            layoutParent.setBackgroundColor(Color.WHITE);
        setupBannerView();
        initWidgetViews();

        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void onVisible() {
        Logger.e("========homepage onvisible");
        getWidgets();
    }

    private void setupBannerView(){
        vpBanner.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, DeviceInfo.screenWidth / 2));
        vpBanner.setHintView(new RectShapeHintView(mContext, R.mipmap.ic_indicator_selected, R.mipmap.ic_indicator_normal));
        vpBanner.setPlayDelay(3000);
        vpBanner.setAnimationDurtion(500);
        List<BannerInfo> bannerList = new ArrayList<BannerInfo>();

        bannerList.add(new BannerInfo(R.drawable.banner1));
        bannerList.add(new BannerInfo(R.drawable.banner2));

        BannerListAdapter bannerListAdapter = new BannerListAdapter(mContext, bannerList);
        vpBanner.setAdapter(bannerListAdapter);
    }

    private void initWidgetViews(){
        initAppWidgetView();
        initAnnouncementWidgetView();
//        initTimetableWidgetView();
        initNewsWidgetView();
//        initWidgetManagerView();
    }

    private void initAppWidgetView(){
        final AppWidgetView widgetView = new AppWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetViewMap.put(AppWidgetInfo.TYPE_APP, widgetView);

    }

    private void initAnnouncementWidgetView(){
        AnnouncementWidgetView widgetView = new AnnouncementWidgetView(mContext);
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetViewMap.put(AppWidgetInfo.TYPE_ANNOUNCEMENT, widgetView);
    }

    private void initTimetableWidgetView(){
        TimetableWidgetView widgetView = new TimetableWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetViewMap.put(AppWidgetInfo.TYPE_TIMETABLE, widgetView);
    }

    private void initNewsWidgetView(){
        NewsWidgetView widgetView = new NewsWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetViewMap.put(AppWidgetInfo.TYPE_NEWS, widgetView);
    }

    private void initWidgetManagerView(){
        View widgetView = LayoutInflater.from(mContext).inflate(R.layout.view_widget_manager, null);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, WidgetManagerActivity.class);
                mContext.startActivity(intent);
            }
        });
        widgetViewMap.put(AppWidgetInfo.TYPE_WIDGET_MANAGER, widgetView);
    }

    private void initMeetingWidgetView(){
        MeetingWidgetView widgetView = new MeetingWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetViewMap.put(AppWidgetInfo.TYPE_MEETING, widgetView);
    }

    private void initEmailWidgetView(){
        EmailWidgetView widgetView = new EmailWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetViewMap.put(AppWidgetInfo.TYPE_EMAIL, widgetView);
    }

    private void initCampusCardWidgetView(){
        CampusCardWidgetView widgetView = new CampusCardWidgetView(mContext);
        widgetView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        widgetView.setOnEnterAppListener(onEnterAppListener);
        widgetViewMap.put(AppWidgetInfo.TYPE_CAMPUS_CARD, widgetView);
    }

    private void getWidgets(){
        boolean isVisitor = UserInfoManager.isVisitor();
        String widgetStr = (String) SharedPrefrencesUtil.get(
                isVisitor ? SharedPreferencesKey.KEY_VISITOR_WIDGET
                        : SharedPreferencesKey.KEY_USER_WIDGET, "");
        if(TextUtils.isEmpty(widgetStr)){
            if(isVisitor){
                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_APP));
                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_NEWS));
//                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_WIDGET_MANAGER));
                widgetStr = JSON.toJSONString(widgetList);
                SharedPrefrencesUtil.put(SharedPreferencesKey.KEY_VISITOR_WIDGET, widgetStr);
            }else {
                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_APP));
                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_ANNOUNCEMENT));
//                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_TIMETABLE));
                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_NEWS));
//                widgetList.add(new AppWidgetInfo(AppWidgetInfo.TYPE_WIDGET_MANAGER));
                widgetStr = JSON.toJSONString(widgetList);
                SharedPrefrencesUtil.put(SharedPreferencesKey.KEY_USER_WIDGET, widgetStr);
            }
        }else{
            widgetList = JSON.parseArray(widgetStr, AppWidgetInfo.class);
        }

        layoutWidget.removeAllViews();
        List<AppWidgetInfo> realWidgetList = new ArrayList<>();
        for(int i = 0; i < widgetList.size(); i++){
            int type = widgetList.get(i).id;
            if(widgetList.get(i).isOpen) {
                View widgetView = widgetViewMap.get(type);
                if (widgetView != null) {
                    LinearLayout parent = (LinearLayout) widgetView.getParent();
                    if (parent != null) {
                        parent.removeView(widgetView);
                    }
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) widgetView.getLayoutParams();
                    params.setMargins(0, i > 0 ? DensityUtil.dip2px(mContext, 4) : 0, 0, 0);
                    widgetView.setLayoutParams(params);
                    layoutWidget.addView(widgetView);
                    realWidgetList.add(widgetList.get(i));
                    switch (type) {
                        case AppWidgetInfo.TYPE_APP:
                            ((AppWidgetView) widgetView).bindData();
                            break;
                        case AppWidgetInfo.TYPE_ANNOUNCEMENT:
                            ((AnnouncementWidgetView) widgetView).bindData();
                            break;
//                    case AppWidgetInfo.TYPE_TIMETABLE:
//                        ((TimetableWidgetView) widgetView).bindData();
//                        break;
                        case AppWidgetInfo.TYPE_NEWS:
                            ((NewsWidgetView) widgetView).bindData();
                            break;
                    }
                }
            }
        }
        String realWidget = JSON.toJSONString(realWidgetList);
        SharedPrefrencesUtil.put(SharedPreferencesKey.KEY_USER_WIDGET, realWidget);
    }

    @Event(value = {R.id.iv_search, R.id.iv_qr_code}, type = View.OnClickListener.class)
    private void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                break;
            case R.id.iv_qr_code:
                break;
        }
    }

//    private class CampusAppAdapter extends PagerAdapter {
//        private List<CampusAppInfo> dataList = new ArrayList<>();
//        private Context context;
//
//        public CampusAppAdapter(Context context, List<CampusAppInfo> dataList) {
//            this.context = context;
//            this.dataList = dataList;
//        }
//
//        @Override
//        public boolean isViewFromObject(View view, Object object) {
//            return view == object;
//        }
//
//        @Override
//        public int getCount() {
//            int size = dataList.size();
//            if (size == 0) return 0;
//            int count = size / 8;
//            if (size % 8 > 0)
//                count++;
//            return count;
//        }
//
//        @Override
//        public int getItemPosition(Object object) {
//            return POSITION_NONE;
//        }
//
//        @Override
//        public void destroyItem(ViewGroup container, int position, Object object) {
//
//        }
//
//        @Override
//        public Object instantiateItem(ViewGroup container, final int position) {
//            View itemView = container.getChildAt(position);
//            if (itemView == null) {
//                GridView gridView = new GridView(context);
//                gridView.setGravity(Gravity.CENTER);
//                gridView.setCacheColorHint(Color.TRANSPARENT);
//                gridView.setNumColumns(4);
//                gridView.setVerticalSpacing(1);
//                gridView.setVerticalScrollBarEnabled(false);
//
//                itemView = gridView;
//                container.addView(itemView);
//            }
//            List<CampusAppInfo> appList = new ArrayList<CampusAppInfo>();
//            for (int i = 0; i < 8; i++) {
//                int index = position * 8 + i;
//                if (index < dataList.size()) {
//                    appList.add(dataList.get(index));
//                }
//            }
//            ((GridView) itemView).setAdapter(new CampusAppGridAdapter(context, appList));
//            ((GridView) itemView).setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//                    if (position == getCount() - 1 && pos == parent.getCount() - 1 && allAppList.size() > 0) {
//                        Intent intent = new Intent(mContext, AppManagerActivity.class);
//                        intent.putExtra("data", (Serializable) allAppList);
//                        mContext.startActivity(intent);
//                    }else{
//                        CampusAppInfo info = (CampusAppInfo) parent.getItemAtPosition(pos);
//                        CampusAppManager.skipToChildApplication(mContext, info);
//
//                    }
//                }
//            });
//            return itemView;
//        }
//
//    }
//
//    private class CampusAppGridAdapter extends AbsAdapter<CampusAppInfo> {
//        public CampusAppGridAdapter(Context context, List<CampusAppInfo> dataList) {
//            super(context, dataList, R.layout.item_campus_app_grid);
//        }
//
//        @Override
//        public void convert(AdapterViewHolder holder, CampusAppInfo data) {
//            ImageView icon = holder.getView(R.id.iv_app_icon);
//            icon.setImageResource(data.getIconRes());
//            TextView name = holder.getView(R.id.tv_app_name);
//            name.setText(data.getName());
//        }
//    }

    private class RectShapeHintView extends ShapeHintView {
        private int focusResId;
        private int normalResId;

        public RectShapeHintView(Context context, @DrawableRes int focusResId, @DrawableRes int normalResId) {
            super(context);
            this.focusResId = focusResId;
            this.normalResId = normalResId;
        }

        @Override
        public Drawable makeFocusDrawable() {
            Drawable drawable = getContext().getResources().getDrawable(focusResId);
            return drawable;
        }

        @Override
        public Drawable makeNormalDrawable() {
            Drawable drawable = getContext().getResources().getDrawable(normalResId);
            return drawable;
        }
    }
}